package com.framework.admin.controller;

import com.framework.admin.model.SysDept;
import com.framework.admin.service.IDeptService;
import com.framework.common.domain.ParamPage;
import com.framework.common.domain.ResultData;
import com.framework.common.util.ParamUtils;
import com.framework.common.vo.TreeNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "dept", tags = "部门管理")
public class DeptController {
    @Autowired
    private IDeptService deptService;

    @ApiOperation("获取部门接口")
    @GetMapping("list")
    public ResultData deptList(SysDept sysDept) {
        if (ParamUtils.isNull(sysDept.getPid())) {
            sysDept.setPid("0");
        }

        List<SysDept> list = deptService.deptList(sysDept);
        return ResultData.data(list);
    }

    @ApiOperation("分页获取部门接口")
    @GetMapping("page")
    public ResultData deptPage(SysDept sysDept, ParamPage page) {
        PageRequest request = PageRequest.of(page.getPageNo(), page.getPageSize());

        Page<SysDept> list = deptService.deptPage(sysDept, request);
        return ResultData.data(list);
    }

    @ApiOperation("获取部门树接口")
    @GetMapping("tree")
    public ResultData<List<TreeNode<SysDept>>> deptTree(SysDept sysDept)  {
        List<TreeNode<SysDept>> list = deptService.deptTree(sysDept);
        return ResultData.data(list);
    }

    /**
     * 保存部门
     */
    @ResponseBody
    @ApiOperation(value = "保存部门")
    @PostMapping(value = "/save")
    @PreAuthorize("hasAuthority('100')")
    public ResultData<String> save(@RequestBody SysDept sysDept) {
        if (StringUtils.isEmpty(sysDept.getPid())) {
            sysDept.setPid("0");
        }
        deptService.save(sysDept);
        return ResultData.success();
    }

    /**
     * 删除部门
     */
    @ResponseBody
    @ApiOperation(value = "删除部门")
    @PostMapping(value = "/del")
    @PreAuthorize("hasAuthority('100')")
    public ResultData<String> del(@RequestBody List<String> ids) {
        deptService.delete(ids);
        return ResultData.success();
    }

}
